package ui;

import java.awt.Color;
import java.awt.Font;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import java.io.File;
import java.io.IOException;

import java.sql.SQLException;

import javax.imageio.ImageIO;

import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.UIManager;

import util.ImagePanel;

import model.Employee;

import controller.EmployeeController;

public class LoginUI implements ActionListener
{
	private static LoginUI instance = null;

	private EmployeeController employeeCtrl;

	private JFrame frameLoginUI;

	private JPanel redBar;

	private JButton loginMenuButtonLogIn;

	private JTextField loginMenuTextFieldUsername;

	private JPasswordField loginMenuPasswordFieldPassword;

	private JLabel loginMenuLabelUsername;
	private JLabel loginMenuLabelPassword;
	private JLabel loginMenuLabelTitle;

	private Image image = null;
	private ImagePanel content;

	private Employee currentLoggedEmployee;
	
	private backButton back;

	public void display()
	{
		frameLoginUI.setSize(700, 400);
		frameLoginUI.setVisible(true);
		frameLoginUI.setResizable(false);
		frameLoginUI.setLocationRelativeTo(null);
	}

	public LoginUI()
	{
		back = new backButton();
		back.clearFile();
		frameLoginUI = new JFrame("Vaizdine Reklama");
		frameLoginUI.addWindowListener(
				new WindowAdapter() 
				{
					public void windowClosing(WindowEvent we) 
					{ 
						System.exit(0);
					}
				}
				);
		employeeCtrl = new EmployeeController();

		loginMenuLabelUsername = new JLabel("Username:");
		loginMenuLabelPassword = new JLabel("Password:");

		loginMenuLabelTitle = new JLabel("LOGIN MENU");
		loginMenuLabelTitle.setBounds(5, 0, 133, 28);
		loginMenuLabelTitle.setForeground(Color.WHITE);
		loginMenuLabelTitle.setFont(new Font("Dialog", Font.BOLD, 20));

		loginMenuTextFieldUsername = new JTextField();
		loginMenuPasswordFieldPassword = new JPasswordField();

		loginMenuButtonLogIn = new JButton();
		loginMenuButtonLogIn.setOpaque(false);
		loginMenuButtonLogIn.setText("Connect");
		loginMenuButtonLogIn.addActionListener(this);

		try
		{
			image = ImageIO.read(new File("img/background/background.jpg"));
		} 
		catch (IOException e)
		{
			System.out.println("[ERROR] Cannot load background : " + e);
			e.printStackTrace();
		}

		redBar = new JPanel();
		redBar.setBackground(new Color(165, 42, 42));
		content = new ImagePanel(image);
		content.setBounds(0, 31, 694, 311);

		frameLoginUI.setContentPane(redBar);

		redBar.add(content);
		redBar.add(loginMenuLabelTitle);
		redBar.setLayout(null);

		content.add(loginMenuLabelUsername);
		content.add(loginMenuLabelPassword);
		content.add(loginMenuPasswordFieldPassword);
		content.add(loginMenuTextFieldUsername);
		content.add(loginMenuButtonLogIn);

		GroupLayout gl_content = new GroupLayout(content);
		gl_content.setHorizontalGroup(
				gl_content.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_content.createSequentialGroup()
						.addGroup(gl_content.createParallelGroup(Alignment.LEADING)
								.addGroup(gl_content.createSequentialGroup()
										.addGap(220)
										.addGroup(gl_content.createParallelGroup(Alignment.TRAILING)
												.addComponent(loginMenuLabelPassword)
												.addComponent(loginMenuLabelUsername))
												.addGap(18)
												.addGroup(gl_content.createParallelGroup(Alignment.LEADING, false)
														.addComponent(loginMenuTextFieldUsername)
														.addComponent(loginMenuPasswordFieldPassword, GroupLayout.DEFAULT_SIZE, 142, Short.MAX_VALUE)))
														.addGroup(gl_content.createSequentialGroup()
																.addGap(284)
																.addComponent(loginMenuButtonLogIn, GroupLayout.PREFERRED_SIZE, 102, GroupLayout.PREFERRED_SIZE)))
																.addContainerGap(262, Short.MAX_VALUE))
				);
		gl_content.setVerticalGroup(
				gl_content.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_content.createSequentialGroup()
						.addGap(98)
						.addGroup(gl_content.createParallelGroup(Alignment.BASELINE)
								.addComponent(loginMenuLabelUsername)
								.addComponent(loginMenuTextFieldUsername, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
								.addGap(26)
								.addGroup(gl_content.createParallelGroup(Alignment.BASELINE)
										.addComponent(loginMenuLabelPassword)
										.addComponent(loginMenuPasswordFieldPassword, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
										.addGap(60)
										.addComponent(loginMenuButtonLogIn, GroupLayout.PREFERRED_SIZE, 22, GroupLayout.PREFERRED_SIZE)
										.addContainerGap(68, Short.MAX_VALUE))
				);
		content.setLayout(gl_content);
		redBar.add(content);
		redBar.add(loginMenuLabelTitle);
	}

	/**
	 * A listener only used on the click of the login button to check if we have such user
	 * 
	 * @param 	e		the action which has triggered it
	 * 
	 * @return 	void 
	 */
	@Override
	public void actionPerformed(ActionEvent e)
	{
		if (e.getSource() == loginMenuButtonLogIn)
		{
			String loginUsername = loginMenuTextFieldUsername.getText();
			char[] loginPassword = loginMenuPasswordFieldPassword.getPassword();

			if ((loginUsername.trim().length() == 0) || (loginPassword.length == 0))
			{
				msgError("You have left empty fields");
			}
			else 
			{
				try
				{
					int employeeID = employeeCtrl.checkLogin(loginUsername, loginPassword);

					if (employeeID > 0)
					{
						try
						{
							currentLoggedEmployee = employeeCtrl.searchEmployeeID(employeeID);
							
							frameLoginUI.setVisible(false);
							MenuUI mainMenu = MenuUI.getInstance();
							mainMenu.display();
						}
						catch (SQLException ex)
						{
							msgError("Could not load logged employee");
						}
					}
					else 
					{
						msgError("The combination of username and password is wrong");
					}
				}
				catch (SQLException ex)
				{
					msgError("Could not check for username and password match");
				}
			}
		}
	}

	/**
	 * Returns the current logged in employee
	 * 
	 * @return 	Employee
	 */
	public Employee getCurrentLoggedEmployee()
	{
		return currentLoggedEmployee;
	}

	/**
	 * Shows an error dialog
	 * 
	 * @param	error	the error 
	 * 
	 * @return 	void
	 */
	private void msgError(String error)
	{
		JOptionPane.showConfirmDialog(null, error, "Error", JOptionPane.PLAIN_MESSAGE, JOptionPane.ERROR_MESSAGE);
	}

	public static LoginUI getInstance()
	{
		if(instance == null)
			instance = new LoginUI();

		return instance;
	}

	public static void main(String[] args)
	{
		try 
		{
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 

			LoginUI loginUI = new LoginUI();
			loginUI.display();
		}
		catch(Exception e)
		{
			JOptionPane.showMessageDialog(null, "Log in menu could not load", "Error", JOptionPane.ERROR_MESSAGE);
		}
	}
}